package rainy.file.synchronization.log;

import java.util.HashMap;
import java.util.Map;

public class MDC {
	private static final ThreadLocal<Map<String, String>> mdcContainer = new ThreadLocal<>();
	private static final Map<String, String> gmdcContainer = new HashMap<>();

	/**
	 * 当前线程上下文中注入某某个值，以便打印日志使用
	 * 
	 * @param key
	 * @param value
	 */
	public static void push(String key, String value) {
		Map<String, String> map = mdcContainer.get();
		if (map == null) {
			map = new HashMap<>();
			mdcContainer.set(map);
		}
		map.put(key, value);
	}

	/**
	 * 向全局变量中注入某个值
	 * 
	 * @param key
	 * @param value
	 */
	public static void gPush(String key, String value) {
		gmdcContainer.put(key, value);
	}

	/**
	 * 全局变量中获取
	 * 
	 * @param key
	 * @return
	 */
	public static String gGet(String key) {
		return gmdcContainer.get(key);
	}

	/**
	 * 从当前线程上下文中获取
	 * 
	 * @param key
	 * @return
	 */
	public static String get(String key) {
		Map<String, String> map = mdcContainer.get();
		if (map == null) {
			return null;
		}
		return map.get(key);
	}
}
